﻿using Microsoft.Extensions.Logging;
using SqlSugar;

namespace Admin.Crypto
{
    /// <summary>
    /// SqlSugar 实体仓储
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class SqlSugarRepository<T> : SimpleClient<T> where T : class, new()
    {
        private ILogger logger;

        protected SqlSugarRepository(ISqlSugarClient client, ILoggerFactory loggerFactory) 
        {
            logger = loggerFactory.CreateLogger(typeof(SqlSugarRepository<T>));
            this.Context = client;
            InitAopEvent();
        }

        protected virtual void InitAopEvent()
        {
            this.Context.Aop.OnLogExecuting = (sql, pars) =>
            {
                var log = $"【{DateTime.Now}——执行SQL】\r\n{UtilMethods.GetNativeSql(sql, pars)}\r\n";
                var originColor = Console.ForegroundColor;
                if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
                    Console.ForegroundColor = ConsoleColor.Green;
                if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
                    Console.ForegroundColor = ConsoleColor.Yellow;
                if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
                    Console.ForegroundColor = ConsoleColor.Red;

                Console.WriteLine(log);
                Console.ForegroundColor = originColor;

                logger?.LogDebug(log);
            };
        }
    }
}
